use strict;
use Test::More tests => 33;

BEGIN { use_ok( 'StatuSync::User' ); }

my $class = 'StatuSync::User';

isa_ok( $class->dbh, 'DBI::db', "DBI database handle (dbh)" );

# create

my $user1 = $class->create({ email => 'yeOnMippuf@mail.com', password => 'nafaliaHac' });
ok( $user1 && ref($user1) eq $class, "create" );
ok( $user1->id > 0, "id" );
is( $user1->email, 'yeOnMippuf@mail.com', "email accessor" );
is( $user1->password, 'nafaliaHac', "password accessor" );

my $user2 = $class->create({ email => 'winjetOf6@mail.com' });
ok( $user2 && ref($user2) eq $class, "create" );
ok( $user2->id > 0, "id" );
is( $user2->email, 'winjetOf6@mail.com', "email accessor" );
is( $user2->password, undef, "password accessor (empty)" );

# retrieve

my $user = $class->find({ email => 'yeOnMippuf@mail.com' });
ok( $user && ref($user) eq $class, "find" );
is( $user->id, $user1->id, "id" );
is( $user->email, 'yeOnMippuf@mail.com', "email" );
is( $user->password, 'nafaliaHac', "password" );

# update

ok( $user->update({ password => 'liaHacnafa9762cei3d5t2369' }), "update" );
is( $user->password, 'liaHacnafa9762cei3d5t2369', "updated password" );
my $user3 = $class->find({ password => 'liaHacnafa9762cei3d5t2369' });
ok( $user3 && ref($user3) eq $class, "find" );
is( $user3->password, 'liaHacnafa9762cei3d5t2369', "updated password" );
is_deeply( $user3, $user, "deep compare" );

my @users = $class->search({ limit => 2 });
ok( @users == 2, "search with limit" );
isa_ok( $users[0], $class );
isa_ok( $users[1], $class );
 
@users = $class->search({ email => 'winjetOf6@mail.com' });
ok( @users == 1, "search by email" );
isa_ok( $users[0], $class );
is( $users[0]->id, $user2->id, "id" );
is( $users[0]->password, undef, "password" );

$users[0]->delete;
$user->delete;

ok( !$class->find({ email => 'yeOnMippuf@mail.com' }), "find deleted" );
ok( !$class->find({ email => 'winjetOf6@mail.com' }), "find deleted" );

my $twuser = new_ok( $class => [{ tw_username => 'statusync' }], 'new user' );
is( $twuser->tw_id, undef, 'tw_id undef' );
is( $twuser->tw_username, 'statusync', 'tw_username' );
is( $twuser->get_twitter_id, '102537968', 'get_twitter_id' );
is( $twuser->tw_id, '102537968', 'tw_id' );

